import {defineMock} from "vite-plugin-mock-dev-server";
import {AjaxResult} from "@/entityType/AjaxResult.ts";
import {TableData} from "@/views/dashboard/TableData.ts";
import fs from "fs";
import path from "path";
import {createTcpProxy, createUdpProxy} from "./createProxy.ts";
import {Socket} from "dgram";
import {Server} from "net";

let proxyFilePath = path.join(__dirname, './proxy.json')

function getProxyData() {
    let str = fs.readFileSync(proxyFilePath, 'utf8').trim()
    if (str) {
        return JSON.parse(str) as TableData[]
    }
    return [] as TableData[]
}

function writeProxyData(tableList) {
    fs.writeFileSync(proxyFilePath, JSON.stringify(tableList), 'utf8')
}

interface ProxyItem {
    id: string;
    a: Socket | Server;
}

const proxyList: ProxyItem[] = []

async function createProxy(item:TableData) {
    const find = proxyList.find(i => i.id === item.id)
    if (!find) {
        let a
        if (item.protocol === 'tcp') {
            a = await createTcpProxy(item)
        } else if (item.protocol === 'udp') {
            a = await createUdpProxy(item)
        }
        if (a) {
            proxyList.push({
                id: item.id,
                a,
            })
        }
    }
}

function deleteProxy(item:TableData) {
    const findIndex = proxyList.findIndex(i => i.id === item.id)
    if (findIndex>-1) {
        proxyList.splice(findIndex,1).forEach((item) => {
            item.a.close()
        })
    }
}

getProxyData().forEach(async (item) => {
    try {
        await createProxy(item)
    }catch(err) {

    }
})

// 进程退出处理（可选）
process.on('SIGINT', () => {
    console.log('收到退出信号，正在关闭所有代理...');
    proxyList.forEach(item => {
        item.a.close()
    })
    process.exit(0);
});

export default defineMock([
    {
        url: import.meta.env.VITE_BASE_API + '/proxy/add',
        method: 'POST',
        status: 200,
        // 可以使用函数，更灵活
        body: (req) => {
            let tableItem = req.body as TableData
            console.log(tableItem)
            let tableList = getProxyData()
            tableList.push(tableItem)
            writeProxyData(tableList)
            return AjaxResult.success({})
        }
    },
    {
        url: import.meta.env.VITE_BASE_API + '/proxy/getList',
        method: 'POST',
        status: 200,
        // 可以使用函数，更灵活
        body: (req) => {
            let tableList = getProxyData()
            tableList.forEach(item => {
                let find = proxyList.find(i=>i.id === item.id)
                if (find) {
                    item.status = '运行'
                } else {
                    item.status = '停止'
                }
            })
            return AjaxResult.success(tableList)
        }
    },
    {
        url: import.meta.env.VITE_BASE_API + '/proxy/del',
        method: 'POST',
        status: 200,
        // 可以使用函数，更灵活
        body: (req) => {
            let ids = req.body as string[]
            let tableList = getProxyData()
            let findIndex = []
            ids.forEach((id) => {
                let f = tableList.findIndex((item) => item.id === id)
                if (f > -1) {
                    findIndex.push(f)
                }
            })
            findIndex.reverse().forEach((item) => {
                tableList.splice(item, 1).forEach((t) => {
                    deleteProxy(t)
                })
            })
            writeProxyData(tableList)
            return AjaxResult.success({})
        }
    },
    {
        url: import.meta.env.VITE_BASE_API + '/proxy/update',
        method: 'POST',
        status: 200,
        // 可以使用函数，更灵活
        body: async (req) => {
            let item = req.body as TableData
            deleteProxy(item)
            let tableList = getProxyData()
            let find = tableList.findIndex(i => i.id === item.id)
            if (find > -1) {
                tableList[find] = item
            }
            await createProxy(item)
            writeProxyData(tableList)
            return AjaxResult.success({})
        }
    },
    {
        url: import.meta.env.VITE_BASE_API + '/proxy/start',
        method: 'POST',
        status: 200,
        // 可以使用函数，更灵活
        body: async (req) => {
            let item = req.body as TableData
            try {
                await createProxy(item)
                return AjaxResult.success({})
            }catch(err) {
                return AjaxResult.error(err)
            }
        }
    },
    {
        url: import.meta.env.VITE_BASE_API + '/proxy/stop',
        method: 'POST',
        status: 200,
        // 可以使用函数，更灵活
        body: (req) => {
            let item = req.body as TableData
            deleteProxy(item)
            return AjaxResult.success({})
        }
    },
])
